package com.stony.controller;

import com.alibaba.fastjson.JSON;
import com.stony.comm.MediaTypes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * Created by ShiHui on 2014/7/10.
 */

@Controller
@RequestMapping("/test")
public class TestController {

    private static final Logger log = LoggerFactory.getLogger(TestController.class);

    @RequestMapping(value = "/async", produces = MediaTypes.JSON)
    public @ResponseBody
    Callable<Object> callable() {
        return new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                return getData();
            }
        };
    }

    private  Map getData(){
        Map data = new HashMap();
        for (int i = 0; i < 10000; i++) {
            data.put(i, "v_" + i);
        }
        return data;
    }
    private final Queue<DeferredResult<String>> responseBodyQueue = new ConcurrentLinkedQueue<DeferredResult<String>>();


    @RequestMapping("/deferred")
    public @ResponseBody DeferredResult<String> deferredResult() {
        DeferredResult<String> result = new DeferredResult<String>();
        this.responseBodyQueue.add(result);
        return result;
    }

    @Scheduled(fixedRate=2000)
    public void processQueues() {
        for (DeferredResult<String> result : this.responseBodyQueue) {
            result.setResult("Deferred result");
            this.responseBodyQueue.remove(result);
        }
    }

    @RequestMapping(value = "/response", method = RequestMethod.GET)
    public Callable<ResponseEntity<Object>> responseEntityCustomHeaders() {
        return new Callable<ResponseEntity<Object>>() {
            public ResponseEntity<Object> call() throws Exception {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                return new ResponseEntity<Object>(getData(), headers, HttpStatus.OK);
            }
        };
    }

}
